<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/10
 * Time: 16:22
 */

namespace osc\admin\controller;

use think\Controller;
use think\Db;

class EndRemind extends Controller
{

    /**
     * 合约到期提醒接口
     * @return string
     */
    public function remind(){

        $get_token = $this->request->param('token');

        return '请求关闭';
        if($get_token !== 'dd88ca22fae7632'){
            return '请求错误，请求时间为：'.date('Y-m-d H:i:s',time());
        }

        //明天的时间
        $tomorrow = date("Y-m-d",strtotime("+1 day"));

        $b1 = Db::name('contract_b1')->where("end_day",$tomorrow)->where('con_state',0)->field('id,username')->select();
        $b2 = Db::name('contract_b2')->where("end_day",$tomorrow)->where('con_state',0)->field('id,username')->select();

        $data = array_merge($b1,$b2);

        if(!$data){ return '没有合约，请求时间为：'.date('Y-m-d H:i:s',time());}
        //循环调用短信模版发送到期提醒
        foreach($data as $key=>$value){

            $r= osc_service('common','SmsDemo')->remind_contract($value['username']);

        }

        return '合约到期提醒请求成功，请求时间为：'.date('Y-m-d H:i:s',time()).'，请求条数为：'.count($data);

    }

    /**
     * 超过三天直接结束合约的操作
     * @return string
     * @throws \think\Exception
     */
    public function end_day(){
        $get_token = $this->request->param('token');

        return '请求关闭';
        if($get_token !== 'sad12314544'){
            return '请求错误，请求时间为：'.date('Y-m-d H:i:s',time());
        }

        //三天前的时间
        $tomorrow = date("Y-m-d",strtotime("-3 day"));

        $b1 = Db::query("update osc_contract_b1 set state=3 where end_day<'".$tomorrow."' and state <>3 ");

        $b2 = Db::query("update osc_contract_b2 set state=3 where end_day<'".$tomorrow."' and state <>3 ");
        $zong = count($b1)+count($b2);
        return '超过三天结束合约请求成功，请求时间为：'.date('Y-m-d H:i:s',time()).'，请求条数为：'.$zong;

    }


    /**
     * 未上传买入凭证三天后进行扣分操作
     * @return string
     */
    public function credit_score(){
        $get_token = $this->request->param('token');

        if($get_token !== 'a231asd12345'){
            return '请求错误';
        }
        //三天前的时间
        $tomorrow = date("Y-m-d",strtotime("-3 day"));

        $b1 = Db::name('contract_b1')->where("end_day",$tomorrow)->where('buy_state <> 1')->field('id,username,info_id')->select();
        $b2 = Db::name('contract_b2')->where("end_day",$tomorrow)->where('buy_state <> 1')->field('id,username,info_id')->select();

        $data = array_merge($b1,$b2);

        if(!$data){ return '没有需要扣分的合约';}

        /*echo'<pre>';print_r($tomorrow);
        echo'<pre>';print_r($data);exit;*/

        $repulse['num']              = 5;
        $repulse['operator']         = '系统脚本';
        $repulse['level']            = 5;
        $repulse['desc']             = '买入凭证未上传';

        //循环进行扣除信用分
        foreach($data as $value){
            // 启动事务
            Db::startTrans();
            try {
                $repulse['contract_id']      = $value['id'];
                $repulse['type']             = $value['info_id'];
                $repulse['contract_state']   = 2;
                $repulse['username']         = $value['username'];

                $contract_repulse = Db::name('contract_repulse')->insert($repulse);

                $credit_score = Db::name('member')->where('username',$value['username'])->setDec('credit_score',$repulse['num']);

                // 提交事务
                Db::commit();

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
            }

        }

        return '请求成功，请求时间为：'.date('Y-m-d H:i:s',time()).'，扣合约数为：'.count($data);

    }

    /**
     * 每天按比例释放会员吉豆为元宝
     * @return string
     * @throws \think\Exception
     */
    public function jilin_release(){
        $get_token = $this->request->param('token');

        if(session('to_day') == date('Y-m-d')) return '当天已完成请求';
        
        if($get_token !== 'qweqzsd123we'){
            return '请求错误，请求时间为：'.date('Y-m-d H:i:s',time());
        }

        $time = date('Y-m-d',time());
        $holiday = Db::name('holiday')->where('date_dt',$time)->find();

        if($holiday){
            return '当天是节假日请求时间为：'.date('Y-m-d H:i:s',time());
        }

        //查询所有吉豆不为0的用户
        $user_info = Db::name('member')->where('jilt<>0')->where('blacklist',1)->select();

        $this->jilin_handle($user_info);
        exit;
        $map = [
            'dt'			=> date('Y-m-d',time()),
            'bao'			=> Db::name('member')->sum('bao'),
            'jilt'			=> Db::name('member')->sum('jilt'),
            'jilin_bean'	=> Db::name('member')->sum('jilin_bean')
        ];

        Db::name('integral')->insert($map);

        session('to_day',date('Y-m-d'));

        return '吉豆每日释放成功，请求时间为：'.date('Y-m-d H:i:s',time()).'，请求条数为：'.count($user_info);

    }

    /**
     * 操作执行
     * @param $data
     * @return bool
     */
    function jilin_handle($data){

        $rollback = [];
        foreach($data as $key=>$value){
            //获取等级利率
            $rate = get_user_state_rate($value['user_state'],$value['is_pass']);
            if($value['user_state']<=1)
            {
                $rate = $rate +  get_share_total($value['username']);
            }

            //计算当前用户是否已完成收益
            $jilin_ticket = Db::name('jilin_ticket')->where('username',$value['username'])->where('state',1)->sum('money');

            if ($jilin_ticket > $value['self_sales']) $rate = $rate / 2;

            //小于或等于0.01时，进行全部释放
            if($value['jilt'] == 0.01 or $value['jilt'] < 0.01){
                $rate = 1;
            }
            //var_dump($rate);
            // 开启事务
            Db::startTrans();
            try{

                $map = [
                    'username'          => $value['username'],
                    'rate'              => $rate,
                    'num'               => round($rate*$value['jilt'],2),
                    'type'              => 2,
                    'create_time'       => time(),
                ];

                //扣除吉豆增加元宝录入释放记录
                Db::name('member')->where('username',$value['username'])->setDec('jilt',$map['num']);
                Db::name('member')->where('username',$value['username'])->setInc('jilin_bean',$map['num']*0.7);
                Db::name('member')->where('username',$value['username'])->setInc('jilin_bean2',$map['num']*0.3);
                Db::name('release')->insert($map);

                // 更新成功 提交事务
                Db::commit();

            }catch (\Exception $e){
                // 更新失败 回滚事务
                Db::rollback();

                $rollback[$key] = [
                    'username'      => $value['username'],
                    'jilt'          => $value['jilt'],
                    'user_state'    => $value['user_state']
                ];
            }
        }

        if($rollback){
            $this->jilin_handle($rollback);
        }

        return true;
    }


    /**
     * 可用额度每日释放
     * @return string
     */
    public function can_release(){
        return '请求关闭';
        $time = date('Y-m-d',time());

        $rew = Db::query("update osc_member a,osc_delivery b set  a. can_quota = a.stay_quota * 0.1 where a.username = b.username and b.vou_date = '".$time."' and b.state = 3");

        if($rew){
            return '可用额度释放成功，请求时间为：'.date('Y-m-d H:i:s',time());
        }

        return '可用额度释放失败，请求时间为：'.date('Y-m-d H:i:s',time());
    }

    /**
     * 清除一个月未成为vip的新用户赠送吉豆所产生的数据
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function new_member(){
        $get_token = $this->request->param('token');

        if(session('to_day_new') == date('Y-m-d')) return '当天已完成请求';

        if($get_token !== 'dastaweq213sad'){
            return '请求错误，请求时间为：'.date('Y-m-d H:i:s',time());
        }
        //查询普通用户,吉豆不为0并且注册时间超过一个月的用户
        $time = date("Y-m-d ", strtotime("-1 month"));
        $new_user = Db::name('member')
            ->where("user_state=0")
            ->where("jilt <> 0")
            ->where("DATE_FORMAT(FROM_UNIXTIME(regdate),'%Y-%m-%d')<'$time'")
            ->field('uid,username,idcardname,user_state,FROM_UNIXTIME(regdate , "%Y-%m-%d %H:%i:%s") regdate,bao,jilt,jilin_bean')
            ->select();
        //删除查询结果的用户数据
        $data = $this->new_member_handle($new_user,10);
        if ($data){
            session('to_day_new',date('Y-m-d'));
            return '请求成功，清除一个月未成为vip的新用户赠送吉豆所产生的数据，请求时间为：'.date('Y-m-d H:i:s',time()).'，请求条数为：'.count($new_user);
        }
        $msg = '请求失败，清除一个月未成为vip的新用户赠送吉豆所产生的数据，请求时间为：'.date('Y-m-d H:i:s',time()).'，请求条数为：'.count($new_user);
        return json(['msg'=>$msg,'data'=>$new_user]);

    }

    /**
     * 操作执行
     * @param $data array 数组数据
     * @param $num  int  循环次数
     * @return bool
     */
    function new_member_handle($data,$num=false){
        if($num !== false && $num == 0) {
            return;
        }else {
            $num--;
        }
        $rollback = [];
        // 开启事务
        Db::startTrans();
        try{
            foreach($data as $key=>$value){
                Db::name('release')->where('username',$value['username'])->delete();
                Db::name('member')->where('username',$value['username'])->update(['jilt'=>0,'jilin_bean'=>0]);
            }
            // 更新成功 提交事务
            Db::commit();
            return true;
        }catch (\Exception $e){
            // 更新失败 回滚事务
            Db::rollback();
            $this->new_member_handle($rollback,$num);
        }
        return false;
    }
}